package study.springcloud.breaker.sentinel.support.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import study.eggs.result.Results;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局 Block 异常处理器
 */
@Slf4j
@Component
public class GlobalBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       BlockException bex) throws Exception {
        log.error(">>>>>>>>>> 全局 Block 异常处理器", bex);
        String msg = null;
        //限流异常
        if (bex instanceof FlowException) {
            msg = "====== 限流提示 ======";
            FlowException ex = (FlowException) bex;
            FlowRule rule = ex.getRule();
            log.info("{}", JSON.toJSONString(rule));
        }
        //降级异常
        else if (bex instanceof DegradeException) {
            msg = "====== 降级提示 ======";
            DegradeException ex = (DegradeException) bex;
            DegradeRule rule = ex.getRule();
            log.info("{}", JSON.toJSONString(rule));
        }
        //参数热点异常
        else if (bex instanceof ParamFlowException) {
            msg = "热点参数限流";
        }
        //系统异常
        else if (bex instanceof SystemBlockException) {
            msg = "系统规则（负载/...不满足要求）";
        }
        //授权异常
        else if (bex instanceof AuthorityException) {
            msg = "授权规则不通过";
        }

        // http状态码
        response.setStatus(200);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        // pring mvc自带的json操作工具，叫jackson
        Map<String, Object> data = new HashMap();
        data.put("message", msg);
        new ObjectMapper().writeValue(response.getWriter(), Results.ok(data));
    }
}
